import pandas as pd
import warnings
 
warnings.filterwarnings('ignore')


# 商品类
# 属性 类别、名字、单价、库存
class Commodity:
    def __init__(self, category, commodity_name, price, invertory) -> None:
        self.category = category
        self.commodity_name = commodity_name
        self.price = price
        self.invertory = invertory

# 用户类
# 属性 名字、密码、余额
# 方法 购物 --购买什么东西，购买多少斤--》减少余额、减少库存
class User:
    def __init__(self, name, passwd, money) -> None:
        self.name = name
        self.passwd = passwd
        self.money = money
    # 购物功能
    def buy_commodity(self, commodity_obj:Commodity, commodity_count):
        if commodity_obj.invertory >= commodity_count and self.money >= commodity_obj.price*commodity_count:
            self.money -= commodity_obj.price*commodity_count
            commodity_obj.invertory -= commodity_count
            return True
        return False
    # 充值功能
    def recharge(self, money):
        self.money += money
        

class Manage:
    # 当前登录的用户
    current_user = None
    def __init__(self):
        self.load_data()
        self.goods_dict = {}
        for good in self.goods_table.values:
            self.goods_dict[good[0]] = Commodity(good[3], good[1], good[2], good[4])
        self.main()

    # 加载数据
    def load_data(self):
        try:
            self.user_table = pd.read_csv('user.csv', index_col=0)
        except pd.errors.EmptyDataError:
            d1 = {'userName': [], 'passwd': [], 'money': []}
            self.user_table = pd.DataFrame(d1)
        try:
            self.goods_table = pd.read_csv('goods.csv', index_col=0)
        except pd.errors.EmptyDataError:
            d1 = {'goodName': [], 'price': [], 'category': [], 'invertory': []}
            self.goods_table = pd.DataFrame(d1)
        try:
            self.record_table = pd.read_csv('record.csv', index_col=0)
        except pd.errors.EmptyDataError:
            d1 = {'userName': [], 'goodID': [], 'goodNum': []}
            self.record_table = pd.DataFrame(d1)
            
            
    # 用户登录
    def login(self, user_name, user_passwd):
        # 验证用户输入不为空
        if not user_name or not user_passwd:
            print('用户名或密码不能为空')
            return False
        user_data = self.user_table[self.user_table['userName']==user_name]
        # 验证有此用户
        if user_data.empty:
            print('没有此用户')
            return False
        # 验证密码
        if not str(user_data['passwd'].values[0]) == user_passwd:
            print('密码错误')
            return False
        # 登录
        self.current_user = User(user_name, user_passwd, float(user_data['money'].values[0]))
        print('登录成功')
        return True
            
    # 用户注册
    def register(self, user_name, user_passwd):
        if not user_name or not user_passwd:
            print('用户名和密码不能为空')
            return False
        user_data = self.user_table[self.user_table['userName']==user_name]
        if not user_data.empty:
            print('此用户名已经被使用')
            return False
        user = pd.DataFrame({'userName': [user_name], 'passwd': [user_passwd], 'money': [0]})
        self.user_table = pd.concat([self.user_table, user], ignore_index=True)
        print(self.user_table)
        self.user_table.to_csv('user.csv')
        print('注册成功')
        return True
    
    # 记录订单
    def record(self, user_name, good_id, good_count):
        one_record = self.record_table[(self.record_table['userName']==user_name) & (self.record_table['goodID']== good_id)]
        if one_record.empty:
            one_record = pd.DataFrame({'userName': [user_name], 'goodID': [good_id], 'goodNum': [good_count]})
            self.record_table = pd.concat([self.record_table, one_record], ignore_index=True)
        else:
            self.record_table.goodNum[(self.record_table['userName']==user_name) & (self.record_table['goodID']== good_id)] += good_count
        print('记录订单...')
        self.record_table.to_csv('record.csv')
    
    # 显示帮助信息
    @staticmethod
    def help():
        print('%-15s%-s'%('buy', '购物'))
        print('%-15s%-s'%('recharge', '充值'))
        print('%-15s%-s'%('exit', '退出登录'))
        print('%-15s%-s'%('bye', '退出购物系统'))
        print('%-15s%-s'%('umsg', '显示用户信息'))
        
    
    def main(self):
        while True:
            # 在使用购物系统前确保已经登录，不然不能继续往下操作
            while self.current_user is None:
                print('请先登录购物系统...')
                instruction = input('1-登录\n2-注册\n3-退出\n请选择：\n')
                if instruction == '1':
                    user_name = input('用户名：')
                    user_passwd = input('密码：')
                    self.login(user_name, user_passwd)
                    print('-'*50)
                elif instruction == '2':
                    user_name = input('用户名：')
                    user_passwd = input('密码：')
                    self.register(user_name, user_passwd)
                    print('-'*50)
                elif instruction == '3':
                    break
                else:
                    print('请选择1或2')
            if self.current_user is None:
                break
            
            option = input(f'{self.current_user.name}(help)$ ')
            if option == 'exit':
                self.current_user = None
            elif option == 'help':
                self.help()
            elif option == 'recharge':
                money = float(input('你要充值多少：'))
                self.current_user.money +=  money
                self.user_table.money[self.user_table['userName']==self.current_user.name] = self.current_user.money
                self.user_table.to_csv('user.csv')
                print(f'充值成功，余额为：{self.current_user.money}')
            elif option == 'buy':
                print(self.goods_table)
                goodId = input('输入商品ID(按0退出本次购物): ')
                if goodId == '0':
                    continue
                goodCount = input('件数: ')
                if goodId and goodCount:
                    goodId = int(goodId)
                    goodCount = int(goodCount)
                else:
                    continue
                good = self.goods_dict.get(goodId, None)
                if good:
                    self.current_user.buy_commodity(good,goodCount)
                    self.user_table.money[self.user_table['userName']==self.current_user.name] = self.current_user.money
                    self.goods_table.invertory[self.goods_table['id']==goodId] = good.invertory
                    self.record(self.current_user.name, goodId, goodCount)
                    self.user_table.to_csv('user.csv')
                    self.goods_table.to_csv('goods.csv')
                    print(f'购买成功，花费{good.price*goodCount}, 余额为{self.current_user.money}')
                else:
                    print('商品不存在')
            elif option == 'bye':
                break
            elif option == 'umsg':
                print(f'用户名:{self.current_user.name}\n余额：{self.current_user.money}')
            else:
                print('没有此操作')
Manage()
        

